﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoginActioner.cs" company="DissingNelleman">
//   
// All rights reserved. </copyright>
// <summary>
//   The login actioner.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace ServiceLibrary.Actioners
{
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.ServiceModel;

    using ServiceLibrary.Actioners.Base;
    using ServiceLibrary.Hibernate;
    using ServiceLibrary.Services.Queries;

    /// <summary>
    /// The login actioner.
    /// </summary>
    public class LoginActioner : UserNamePasswordValidator
    {
        #region Public Methods and Operators

        /// <summary>
        /// The validate.
        /// </summary>
        /// <param name="userName">
        /// The user name.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <exception cref="SecurityTokenException">
        /// </exception>
        /// <exception cref="FaultException">
        /// </exception>
        public override void Validate(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                throw new SecurityTokenException("Username and password required");
            }

            bool isValid = NHibernateProvider.Instance.WithSession(
                hsession =>
                    {
                        var userActioner = new UserActioner(hsession, null);
                        var validationQuery = new ValidateUserQuery();
                        validationQuery.Username = userName;
                        validationQuery.Password = password;
                        return userActioner.ValidateLoginBoolean(validationQuery);
                    });

            if (!isValid)
            {
                throw new FaultException(string.Format("Wrong username ({0}) or password ", userName));
            }
        }

        #endregion
    }
}